#!/bin/bash
# 执行：sh git_url_to_gitlab_api_url.sh http://aaa.gitlab.com/feg/fea-testing.git
# 结果：http://aaa.gitlab.com/api/v4/projects/feg%2Ffea-testing
cd `dirname "$0"`

if [ $# -ne 2 ] ;then
  echo "本脚本用于将通过gitlab的http的git地址和token 取项目id"
  echo "使用sh git_url_to_gitlab_api_url.sh 某某.git 某某token"
  exit
fi

gitlab_git_real_address=$1
gitlab_token=$2

# 1.通过git地址获取域名 git.imagedt.com
gitlab_com_url=`echo $gitlab_git_real_address | cut -d/ -f3`
echo ${gitlab_com_url}
# 2.获取项目路径
# idt-muskmelon-front-dashboard-kimberly.git
last_string=`echo $gitlab_git_real_address | rev |cut -d/ -f1 |rev`

# imagedt_feg/dashboard/idt-muskmelon-front-dashboard-kimberly.git
medium_string=`echo $gitlab_git_real_address | sed -e 's#http://'"$gitlab_com_url"'/##g'`

# imagedt_feg/dashboard/
project_origin_path=`echo ${medium_string} | sed -e 's#'"${last_string}"'##g'`

# 替换/为%2F，取得项目路径imagedt_feg%2Fdashboard%2F
project_path=`echo ${project_origin_path} | sed 's#/#%2F#g'`

# 3.项目名称
gitlab_project_name=`echo ${last_string} | cut -d. -f1`

# 4.获取到project id
project_id=`curl -XGET -H "Content-Type: application/json" --header "PRIVATE-TOKEN: $gitlab_token" http://$gitlab_com_url/api/v4/projects/${project_path}${gitlab_project_name} | python -c 'import sys, json; print(json.load(sys.stdin)["id"])'`

echo $project_id
